<template>
  <div>
    <div class="bread-box but20">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item class="btn-green" style=" color: #3DC094;" @click.native="goBack">门店建设整体跟进</el-breadcrumb-item>
        <el-breadcrumb-item> {{ typeFlag === 'edit' ? '编辑': '新增' }}</el-breadcrumb-item>
      </el-breadcrumb>
      <div>
        <el-button type="primary" size="mini" @click.native="submitForm('save')">保存</el-button>
        <el-button size="mini" @click.native="goBack">返回</el-button>
      </div>
    </div>
    <div class="mt20">
      <div class="qup-title-box">
        <span class="border" /><span>门店建设整体跟进</span>
      </div>
      <el-form ref="refForm" :model="formData" :rules="formRules" size="mini" label-width="150px">
        <el-row class="form_item_height">
          <el-col :span="8">
            <el-form-item label="门店建设项目号:" prop="constCode"> {{ formData.constCode }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="门店建设整体进度:" prop="constSchedule"> {{ formaterData(beforeConstSchedule, formData.constSchedule) }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="门店:" prop="shopName"> {{ formData.shopName }}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="所属客户:" prop="clientName"> {{ formData.clientName }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属办事处:" prop="officeName"> {{ formData.officeName }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="门店类型:" prop="shopType"> {{ formaterData(shopTypeList, formData.shopType) }}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="门店业务类型:" prop="shopBizType"> {{ formaterArr(shopBizTypeList, formData.shopBizType) }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="门店城市级别:" prop="shopCityLevel"> {{ formaterData(cityLevelList, formData.shopCityLevel) }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="门店市场层级:" prop="shopMarketLevel"> {{ formaterData(marketLevelList, formData.shopMarketLevel) }}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="门店详细地址:" prop="shopAddress"> {{ formData.shopAddress }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="报图类型:" prop="marketType"> {{ formaterData(marketTypeList, formData.marketType) }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="门店建设类型:" prop="constType"> {{ formaterData(constTypeList, formData.constType) }}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="商家类别:" prop="bizmanType"> {{ formaterData(bizmanTypeList, formData.bizmanType) }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="装修形式:" prop="decorationForm"> {{ formaterArr(decorationFormList, formData.decorationForm) }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="装修范围:" prop="decorationRange"> {{ formaterArr(decorationRangeList, formData.decorationRange) }}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="是否交接市场:" prop="isHandover"> {{ formaterData(booleansList, formData.isHandover) }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="交接前门店:" prop="beforeShopName"> {{ formData.beforeShopName }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="交接前门店建设整体进度:" prop="beforeConstSchedule"> {{ formaterData(beforeConstSchedule, formData.beforeConstSchedule) }}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="市场交接时间:" prop="handoverApplyTime"> {{ formData.handoverApplyTime }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="门店建设是否完结:" prop="isEnd">
              <el-select
                v-model="formData.isEnd"
                placeholder="请选择"
                style="width: 100%"
                @change="handleChange"
              >
                <el-option
                  v-for="item in booleansList"
                  :key="item.dictCode"
                  :label="item.dictName"
                  :value="item.dictCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="门店建设状态:" prop="constState">
              <el-select
                v-model="formData.constState"
                placeholder="请选择"
                style="width: 100%"
                @change="handleChange"
              >
                <el-option
                  v-for="item in constStateList"
                  :key="item.dictCode"
                  :label="item.dictName"
                  :value="item.dictCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8" :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="门店建设跟进说明:" prop="followUpDesc">
              <el-input v-model="formData.followUpDesc" type="textarea" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="预计开业时间:" prop="expectOpenTime"> {{ formData.expectOpenTime }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否开业:" prop="isOpen">
              <el-select
                v-model="formData.isOpen"
                placeholder="请选择"
                style="width: 100%"
                @change="handleChange"
              >
                <el-option
                  v-for="item in booleansList"
                  :key="item.dictCode"
                  :label="item.dictName"
                  :value="item.dictCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实际开业开始时间:" prop="actualOpenTime">{{ formData.actualOpenTime }}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="实际开业结束时间:" prop="actualOpenEndTime">{{ formData.actualOpenEndTime }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否有开业申请:" prop="haveOpenApply">
              <el-select
                v-model="formData.haveOpenApply"
                placeholder="请选择"
                style="width: 100%"
                @change="handleChange"
              >
                <el-option
                  v-for="item in booleansList"
                  :key="item.dictCode"
                  :label="item.dictName"
                  :value="item.dictCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="开业申请示例号:" prop="modifName">{{ formData.openApplySampleNo }}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

  </div>
</template>

<script>
// import imgUpload from '../../components/ImgUploader/ImgUploader'  图片上传组件
import { listByBizCode } from '@/api/dataDict' // 数据字典
import { getDictByPatchType } from '@/api/dataDict'
import { queryEditData, submitEditShopData } from '@/api/storeConstruction'
export default {
  name: 'NewEditor',
  // components: {
  //   imgUpload
  // },
  props: {
    pageShow: {
      type: Boolean,
      default: false,
      required: true
    },
    detailData: {
      type: [String, Object],
      default: ''
    },
    typeFlag: {
      type: String,
      default: 'add'
    },
    stateList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      // 是否
      num: 1, // 默认数量
      isAdd: true,
      index: '',
      oldItems: [], // 编辑时table值
      listByBizCodeList: [], // 价格类型列表
      pricingTypeCodeList: [], // 定价类别
      multipleSelection: [],
      singleSelection: [],
      priceTypeCodeList: [],
      // 门店建设整体进度
      beforeConstSchedule: [],
      constScheduleName: '',
      // 业务类型
      shopBizTypeList: [],
      // 门店类型
      shopTypeList: [],
      // 表单数据
      formData: {
        picUrl: '', // 图片
        items: []

      },
      formRules: {
        isEnd: [
          { required: true, message: '请选择门店建设是否完结' }
        ], // 门店建设是否完结
        constState: [
          { required: true, message: '请选择门店建设状态' }
        ], // 门店建设状态
        followUpDesc: [
          { required: true, message: '请输入门店建设说明' }
        ], // 门店建设跟进说明
        isOpen: [
          { required: true, message: '请选择是否开业' }
        ], // 是否开业
        haveOpenApply: [
          { required: true, message: '请选择是否有开业申请' }
        ] // 是否有开业申请
      },
      booleansList: [
        { dictCode: 1, dictName: '是' },
        { dictCode: 0, dictName: '否' }
      ],
      formDataS: [],
      items: [],
      btnList: [], // 按钮权限
      les: `https://uacdev.quanyou.com.cn/price-center/api/v1/priceWholesaleStandard/search`,
      interfacePath: `https://uacdev.quanyou.com.cn/price-center/api/v1/defPriceType/page` // 调公共接口
    }
  },
  computed: {
    nowvisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },

  async created() {
    this.formData.id = this.detailData.id
    await this.getDictByPatchTypeAll(['BEFORE_CONST_SCHEDULE', 'CONST_STATE', 'MARKET_TYPE',
      'CONST_TYPE', 'BIZMAN_TYPE', 'DECORATION_FORM', 'DECORATION_RANGE', 'BIZ_TYPE',
      'SHOP_TYPE', 'CITY_LEVEL', 'MARKET_LEVEL'])
      .then(res => {
        this.beforeConstSchedule = res.BEFORE_CONST_SCHEDULE // 门店建设整体进度
        this.constStateList = res.CONST_STATE // 门店建设状态
        this.marketTypeList = res.MARKET_TYPE // 报图类型
        this.constTypeList = res.CONST_TYPE // 门店建设类型
        this.bizmanTypeList = res.BIZMAN_TYPE // 商家类别
        this.decorationFormList = res.DECORATION_FORM // 装修形式
        this.decorationRangeList = res.DECORATION_RANGE // 装修范围
        this.shopBizTypeList = res.BIZ_TYPE // 业务类型
        this.shopTypeList = res.SHOP_TYPE // 门店类型
        this.cityLevelList = res.CITY_LEVEL // 城市级别
        this.marketLevelList = res.MARKET_LEVEL // 市场层级
      })
    await this.getManageData(this.formData.id)
    // this.beforeConstSchedule.forEach(item => {
    //   if (item.dictCode === this.formData.beforeConstSchedule) {
    //     this.constScheduleName = item.dictName
    //   }
    // })
  },
  activated() {
  },
  methods: {
    // 获取数据字典
    async getDictByPatchTypeAll(data) {
      const obj = await getDictByPatchType(data)
        .then(res => {
          return res
        })
      return obj
    },
    // 根据ID获取数据
    getManageData(id) {
      queryEditData(id).then(res => {
        this.formData = res.data
      })
    },
    // 格式化数据
    formaterData(arr, dictCode) {
      if (!arr) return
      const tmpArr = arr.filter(item => item.dictCode === dictCode)
      if (tmpArr.length) {
        return tmpArr[0].dictName
      }
      return dictCode
    },
    formaterArr(data, str) {
      if (!data || !data.length || !str || !str.length) return
      let list = []
      if (typeof (str) === 'string') {
        list = str.split(',')
      } else {
        list = str
      }
      const arr = []
      data.forEach((item) => {
        const flag = list.some(v => v === item.dictCode)
        if (flag) {
          arr.push(item.dictName)
        }
      })
      return arr.toString()
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 上样推荐方案接口
    getPriceTypeId() {
      listByBizCode({ pricingTypeCode: '04' }).then(res => {
        if (res.success === 1) {
          this.listByBizCodeList = res.data
        }
      })
    },
    // 新增
    addRow() {
      this.priceTypeCodeList = []
      this.formDataS = this.formData.items
      // 校验items是否都填写

      let stepParam = ''
      this.formData.items.filter(function(item) {
        if (item.pricingTypeCode === '01') {
          stepParam = item.calculateStep
        }
      })
      this.formData.items.push({
        calculateStep: '',
        pricingTypeCode: '',
        priceType: [],
        filtersRaw: [],
        priceTypeCode: '',
        priceTypeName: '',
        priceTypeId: '',
        stepParam: stepParam
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 删除行
    delRow() {
      if (this.multipleSelection.length < 1) {
        this.$message.warning(`请选择【删除】项`)
        return false
      }
      this.$confirm('是否确认删除所选内容?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const mulSelect = this.multipleSelection
        const data = this.formData.items
        this.deleteData = data.filter((item) => {
          const arrlist = mulSelect.map((v) => v.id)
          return arrlist.includes(item.id)
        })
        const newData = data.filter((item) => {
          const arrlist = mulSelect.map((v) => v.calculateStep)
          return !arrlist.includes(item.calculateStep)
        })
        this.$set(this.formData, 'items', newData)
        this.$forceUpdate()
      })
    },
    goBack() {
      this.$confirm('此操作不可逆，是否确认并返回列表界面?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.nowvisible = false
        this.$emit('goBack')
      })
    },
    // 计算步骤校验只能填写正整数
    checkType(row) {
      for (let i = 0; i < this.formDataS.length - 1; i++) {
        if (row.calculateStep === this.formDataS[i].calculateStep) {
          this.$message.warning('计算步骤不能重复,请重新填写')
          row.calculateStep = ''
          return
        }
      }
      const type = typeof row.calculateStep
      if (type !== 'number' || row.calculateStep <= 0) {
        this.$message.warning('请填写正整数')
        row.calculateStep = ''
      }
    },
    // 入参步骤校验只能填写正整数
    checkTypestep(row) {
      const type = typeof row.stepParam
      if (type !== 'number' || row.stepParam <= 0) {
        this.$message.warning('请填写正整数')
        row.stepParam = ''
      }
    },
    // 提交表单处理
    submitForm() {
      this.$refs['refForm'].validate((valid) => {
        if (valid) {
          submitEditShopData(this.formData).then(res => {
            if (res.success) {
              this.$message.success('操作成功')
              this.formData = {}
              this.$refs.refForm.clearValidate()
              this.$emit('goBack')
            }
          })
        }
      })
    },
    // 改变所属定价类别的值
    changePri(row) {
      row.priceTypeCode = ''
      row.priceTypeName = ''
      row.priceType = []

      const filtersRaw = [{ id: 'dr', property: 'dr', value: '0', operator: '=' }]
      if (row.pricingTypeCode) {
        const newFiltersRaw = filtersRaw.concat({ id: 'pricingTypeCode', property: 'pricingTypeCode', value: row.pricingTypeCode, operator: '=' })
        this.$set(row, 'filtersRaw', newFiltersRaw)
      } else {
        this.$set(row, 'filtersRaw', filtersRaw)
      }
    },
    selectionChange(val) {
      this.singleSelection = val
    },
    // 选择：
    changePriceType(row) {
      if (row && row.priceType && row.priceType.length > 0) {
        const data = row.priceType
        row.priceTypeCode = data ? data[0].priceTypeCode : row.priceTypeCode
        row.priceTypeName = data ? data[0].priceTypeName : row.priceTypeName
        row.priceTypeId = data ? data[0].id : row.priceTypeId
        row.calculateModelCode = data ? data[0].calculateModelCode : row.calculateModelCode
      } else {
        row.priceTypeCode = ''
        row.priceTypeName = ''
      }
    },
    // standardCode', title: '价格类型编码' }, { prop: 'standardName

    btnOperate(flag) {
      switch (flag) {
        case 'add':
          this.addRow()
          break
        case 'del':
          this.delRow()
          break
        default:
          break
      }
    }

  }
}
</script>
<style lang='scss' scoped>
  /deep/ .el-breadcrumb__inner{
    color: $qup-color-primary;
  }
.img-upload-container {
  width: fit-content;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-end;
  align-items: center;
  .icon-msg{
    margin-left: 10px;
    color: #999;
  }
}
.subdaoch{margin: 10px 0;}
.but20{ margin-bottom: 20px;}
.el-breadcrumb__inner,.btn-green{
    color: #3DC094;
}
.qup-title-box{background: #f2f2f2; line-height: 30px;}

</style>
